package com.example.juc;

public class InterruptTest {

    static Flag flag=new Flag();

    public static void main(String[] args) {

        test2();

    }


    //中断线程
    private static void test1(){

        Thread t1 = new Thread(() -> {

            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    break;
                }

                //sleep,wait等方法被打断，会抛出异常，并且打断无效
                sleep(500L);

                System.out.println("执行中");
            }

        });

        t1.start();

        sleep(1000L);

        //打断
        new Thread(()->{
            t1.interrupt();
        }).start();

    }


    /**
     * 中断线程
     */
    private static void test2(){
        Thread t1 = new Thread(() -> {

            System.out.println("开始执行");
            while (!flag.flag) {
                //System.out.println("执行中");
            }
            System.out.println("执行完成");

        });

        t1.start();

        sleep(2000L);
        //打断
        Object o = new Object();
        new Thread(()->{
            synchronized (o){
                flag.flag=true;
                System.out.println("中断执行");
            }
        }).start();

    }

    static class Flag{
       //volatile boolean flag=false;
       boolean flag=false;
    }
    private static void sleep(Long time){
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
